package com.digitalchina.lxnsy.activity.old;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;

import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessTraining;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.toolkit.DateStyle;
import com.digitalchina.lxnsy.toolkit.DateUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.xml.UserXML;

import java.util.Calendar;

import butterknife.Bind;
import butterknife.OnClick;
import chihane.jdaddressselector.BottomDialog;
import chihane.jdaddressselector.OnAddressSelectedListener;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;

import static com.digitalchina.lxnsy.activity.old.TrainingInfoUpdateActivity.UPDATE_RESULT_NAME_CODE;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：白彦东
 * 创建时间：2017/2/20 11:17
 * 修改备注：
 * ================================================
 */

public class TrainingInitiateActivity extends BaseActivity {


    @Bind(R.id.initiate_training_tv_name)
    TextView initiateTrainingTvName;
    @Bind(R.id.initiate_training_ll_name)
    LinearLayout initiateTrainingLlName;
    @Bind(R.id.initiate_training_tv_person)
    TextView initiateTrainingTvPerson;
    @Bind(R.id.initiate_training_ll_person)
    LinearLayout initiateTrainingLlPerson;
    @Bind(R.id.initiate_training_tv_date)
    TextView initiateTrainingTvDate;
    @Bind(R.id.initiate_training_ll_date)
    LinearLayout initiateTrainingLlDate;
    @Bind(R.id.initiate_training_tv_place)
    TextView initiateTrainingTvPlace;
    @Bind(R.id.initiate_training_ll_place)
    LinearLayout initiateTrainingLlPlace;
    @Bind(R.id.initiate_training_tv_start_time)
    TextView initiateTrainingTvStartTime;
    @Bind(R.id.initiate_training_ll_start_time)
    LinearLayout initiateTrainingLlStartTime;
    @Bind(R.id.initiate_training_tv_end_time)
    TextView initiateTrainingTvEndTime;
    @Bind(R.id.initiate_training_ll_end_time)
    LinearLayout initiateTrainingLlEndTime;
    @Bind(R.id.initiate_training_btn_submit)
    Button initiateTrainingBtnSubmit;

    private static final int UPDATE_REQUEST_CODE = 666;
    private String provinceCode = "";
    private String cityCode = "";
    private String countyCode = "";
    private boolean isStartTime;
    private String trainingDate;

    private int mYear, mMonth, mDayOfMonth;
    private int sHourOfDay, sMinute; // 开始时间
    private int eHourOfDay, eMinute; // 结束时间

    @Override
    public void setLayout() {
        setTitle("发起培训");
        setContentLayout(R.layout.activity_initiate_training);
    }

    @Override
    public void initMember() {
        initiateTrainingTvPerson.setText(UserXML.getUserTrueName(this)); // TODO 真实姓名?
    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG.MSG_TRAINING_SAVE_SUCCESS:
                        showToast("保存成功");
                        setResult(RESULT_OK);
                        finish();
                        break;
                    case MSG.MSG_TRAINING_SAVE_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {

    }

    @Override
    public void rightOnClick() {

    }

    @OnClick({R.id.initiate_training_ll_name, R.id.initiate_training_ll_date,
            R.id.initiate_training_ll_place, R.id.initiate_training_ll_start_time, R.id.initiate_training_ll_end_time,
            R.id.initiate_training_btn_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.initiate_training_ll_name: // 培训名称
                jumpToActivity("name");
                break;
            case R.id.initiate_training_ll_date: // 培训日期
                showDatePicker();
                break;
            case R.id.initiate_training_ll_place: // 培训地点
                showAddressPicker();
                break;
            case R.id.initiate_training_ll_start_time: // 开始时间
                isStartTime = true;
                showTimePicker();
                break;
            case R.id.initiate_training_ll_end_time: // 结束时间
                isStartTime = false;
                showTimePicker();
                break;
            case R.id.initiate_training_btn_submit: // 提交
                saveTraining();
                break;
        }
    }

    /**
     * 保存数据
     */
    private void saveTraining() {
        if (!isTextEmpty()) {
            String title = StringUtil.getText(initiateTrainingTvName);
            String startTime = StringUtil.getText(initiateTrainingTvStartTime);
            String endTime = StringUtil.getText(initiateTrainingTvEndTime);
            BusinessTraining.initiateTraining(this, title, trainingDate, startTime, endTime,
                    provinceCode, cityCode, countyCode, mHandler);
        }
    }

    /**
     * 判空
     */
    private boolean isTextEmpty() {
        if (StringUtil.isTextEmpty(initiateTrainingTvName)) {
            showToast("请填写培训名称");
            return true;
        }

        if (StringUtil.isTextEmpty(initiateTrainingTvDate)) {
            showToast("请填写培训日期");
            return true;
        }

        if (StringUtil.isTextEmpty(initiateTrainingTvPlace)) {
            showToast("请填写培训地点");
            return true;
        }

        if (StringUtil.isTextEmpty(initiateTrainingTvStartTime)) {
            showToast("请填写开始时间");
            return true;
        }

        if (StringUtil.isTextEmpty(initiateTrainingTvEndTime)) {
            showToast("请填写结束时间");
            return true;
        }

        //start比end早,返回-1,
        //start与end相同,返回0
        //start比end晚,返回1
        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();
        start.set(mYear, mMonth, mDayOfMonth, sHourOfDay, sMinute);
        end.set(mYear, mMonth, mDayOfMonth, eHourOfDay, eMinute);
        if (start.compareTo(end) != -1) {
            showToast("开始时间不能大于结束时间");
            return true;
        }
        return false;
    }

    /**
     * 培训时间选择
     */
    private void showAddressPicker() {
        final BottomDialog bottomDialog = new BottomDialog(this);
        bottomDialog.setOnAddressSelectedListener(new OnAddressSelectedListener() {
            @Override
            public void onAddressSelected(Province province, City city, County county, Street street) {
                provinceCode = province.province_code;
                cityCode = city != null ? city.city_code : "";
                countyCode = county != null ? county.county_code : "";
                if (provinceCode.equals("110000") || provinceCode.equals("120000") || provinceCode.equals("310000") || provinceCode.equals("500000") || (provinceCode.equals("460000") && cityCode.equals("469000")))
                    initiateTrainingTvPlace.setText(String.format("%s %s", province.province_name, county != null ? county.county_name : ""));
                else
                    initiateTrainingTvPlace.setText(String.format("%s %s %s", province.province_name,
                            city != null ? city.city_name : "", county != null ? county.county_name : ""));
                bottomDialog.dismiss();
            }
        });
        bottomDialog.show();
    }

    /**
     * 跳转至修改信息页面
     */
    private void jumpToActivity(String updateWhat) {
        GotoUtil.gotoForResultActivity(this, TrainingInfoUpdateActivity.class, UPDATE_REQUEST_CODE, "training", updateWhat);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == UPDATE_REQUEST_CODE) {
            String updateContent = data.getStringExtra("update");
            if (resultCode == UPDATE_RESULT_NAME_CODE) {
                initiateTrainingTvName.setText(updateContent);
            }
        }
    }

    /**
     * 开始/结束时间选择
     */
    private void showTimePicker() {
        int hourOfday;
        int minute;

        if (StringUtil.isTextEmpty(initiateTrainingTvStartTime)) {
            Calendar calendar = Calendar.getInstance();
            hourOfday = calendar.get(Calendar.HOUR_OF_DAY);
            minute = calendar.get(Calendar.MINUTE);
        } else {
            String[] currentTime = StringUtil.getText(initiateTrainingTvStartTime).split(":");
            hourOfday = Integer.parseInt(currentTime[0]);
            minute = Integer.parseInt(currentTime[1]);
        }

        TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int hourOfday, int minute) {
                String selectTime = hourOfday + ":" + minute;
                if (isStartTime) {
                    sHourOfDay = hourOfday;
                    sMinute = minute;
                    initiateTrainingTvStartTime.setText(DateUtil.StringToString(selectTime, DateStyle.HH_MM));
                } else {
                    eHourOfDay = hourOfday;
                    eMinute = minute;
                    initiateTrainingTvEndTime.setText(DateUtil.StringToString(selectTime, DateStyle.HH_MM));
                }
            }
        }, hourOfday, minute, true);

        timePickerDialog.show();

    }

    /**
     * 显示日期选择
     */
    private void showDatePicker() {

        if (StringUtil.isTextEmpty(initiateTrainingTvDate)) {
            Calendar calendar = Calendar.getInstance();
            mYear = calendar.get(Calendar.YEAR);
            mMonth = calendar.get(Calendar.MONTH);
            mDayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        } else {
            String[] currentDate = StringUtil.getText(initiateTrainingTvDate).split("/");
            mYear = Integer.parseInt(currentDate[0]);
            mMonth = Integer.parseInt(currentDate[1]) - 1;
            mDayOfMonth = Integer.parseInt(currentDate[2]);
        }

        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
                mYear = year;
                String selectDate = year + "/" + (month + 1) + "/" + dayOfMonth;
                trainingDate = year + "-" + (month + 1) + "-" + dayOfMonth;
                initiateTrainingTvDate.setText(DateUtil.StringToString(selectDate, DateStyle.YYYY_MM_DD_EN));
            }
        }, mYear, mMonth, mDayOfMonth);

        datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
        datePickerDialog.show();
    }
}
